package com.smallcc.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 晓风过境
 * @TODO
 * @date 2018/4/3 23:20
 * @day 03
 * @return $text$
 * @title ${CLASS_NAME}
 * @project_name sell
 */
@Component
@Slf4j
@ServerEndpoint("/webSocket")
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();
    @OnOpen
    public void opOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        log.info("[WebSocket消息]你有新的链接,总数:{}",webSocketSet.size());
    }
    @OnClose

    public void OnClose(Session session){
        webSocketSet.remove(this);
        log.info("[WebSocket消息]你有链接断开,总数:{}",webSocketSet.size());
    }
    @OnMessage
    public void onMessage(String message){
        log.info("[WebSocket消息]收到客户端发过来的消息:{}",message);
    }

    public void sendMessage(String message){
        for (WebSocket webSocket:webSocketSet){
            log.info("[WebSocket消息]广播消息,消息{}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
